// Package crons
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package crons

import (
	"context"
	"github.com/gogf/gf/v2/os/gtime"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/cron"
	"hotgo/internal/library/hfsm"
	"hotgo/internal/model/entity"
	"hotgo/internal/service"
	"strconv"
	"time"
)

func init() {
	cron.Register(CloseOrder)
}

// CloseOrder 取消过期订单
var CloseOrder = &cCloseOrder{name: "close_order"}

type cCloseOrder struct {
	name string
}

func (c *cCloseOrder) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cCloseOrder) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	outTime := 3 // 默认3分钟
	if len(parser.Args) != 0 {
		outTime, err = strconv.Atoi(parser.Args[0])
		if err != nil {
			outTime = 3
		}
	}
	var list []entity.Order
	err = service.SysUserOrder().Model(ctx).
		Where(dao.Order.Columns().Status, consts.UserOrderStatusNot).
		WhereLTE(dao.Order.Columns().CreatedAt, gtime.Now().Add(-time.Duration(outTime)*time.Minute)).
		Scan(&list)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute err:%+v", err)
		return
	}
	for _, order := range list {
		if err = hfsm.OFSM.PushState(order.Id, consts.NotToCloseEvent); err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute err:%+v", err)
			continue
		}
		parser.Logger.Info(ctx, "cron CloseOrder Execute order: ", order)
	}
	return
}
